package com.jiawa.train.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.business.domain.*;
import com.jiawa.train.business.mapper.DailyTrainSeatMapper;
import com.jiawa.train.business.req.DailyTrainSeatQueryReq;
import com.jiawa.train.business.req.DailyTrainSeatSaveReq;
import com.jiawa.train.business.resp.DailyTrainSeatQueryResp;
import com.jiawa.train.business.service.DailyTrainSeatService;
import com.jiawa.train.business.service.DailyTrainStationService;
import com.jiawa.train.business.service.TrainSeatService;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zzl
 * @version 1.0
 */
@Service
public class DailyTrainSeatServiceImpl implements DailyTrainSeatService {
    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainSeatServiceImpl.class);

    @Resource
    private DailyTrainSeatMapper dailyTrainSeatMapper;
    @Resource
    private TrainSeatService trainSeatService;
    @Resource
    private DailyTrainStationService dailyTrainStationService;
    @Override
    public void save(DailyTrainSeatSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(req, DailyTrainSeat.class);
        if(ObjectUtil.isNull(dailyTrainSeat.getId())) {
            if(isExist(dailyTrainSeat)) {
                throw new BusinessException(BusinessExceptionEnum.TRAIN_CARRIAGE_SEAT_IS_EXIST);
            } else {
                dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
                dailyTrainSeat.setCreateTime(now);
                dailyTrainSeat.setUpdateTime(now);
                dailyTrainSeatMapper.insert(dailyTrainSeat);
            }
        } else {
            dailyTrainSeat.setUpdateTime(now);
            dailyTrainSeatMapper.updateByPrimaryKeySelective(dailyTrainSeat);
        }
    }

    /**
     * 分页查询每日高铁座位数据
     * @param req
     * @return
     */
    @Override
    public PageResp<DailyTrainSeatQueryResp> queryList(DailyTrainSeatQueryReq req) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.setOrderByClause("date asc, train_code asc, carriage_index asc, carriage_seat_index asc");
        DailyTrainSeatExample.Criteria criteria = dailyTrainSeatExample.createCriteria();
//        if(ObjectUtil.isNotNull(req.getDate())) {
//            criteria.andDateEqualTo(req.getDate());
//        }
        if(ObjectUtil.isNotNull(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }

        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrainSeat> dailyTrainSeatList = dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);

        PageInfo<DailyTrainSeat> pageInfo = new PageInfo<>(dailyTrainSeatList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainSeatQueryResp> dailyTrainSeatQueryRespList = BeanUtil.copyToList(dailyTrainSeatList, DailyTrainSeatQueryResp.class);

        PageResp<DailyTrainSeatQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(dailyTrainSeatQueryRespList);

        return pageResp;
    }

    @Override
    public void delete(Long id) {
        dailyTrainSeatMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据日期、高铁，生成每日高铁座位数据
     * @param date
     * @param train
     */
    @Transactional
    @Override
    public void genDailyTrainSeat(Date date, Train train) {
        LOG.info("生成日期【{}】车次【{}】的座位信息开始", DateUtil.formatDate(date), train.getCode());

        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(train.getCode());
        // 1.删除指定高铁座位数据
        dailyTrainSeatMapper.deleteByExample(dailyTrainSeatExample);

        // 2.根据高铁车次查询高铁座位数据，判断是否为空
        List<TrainSeat> trainSeatList = trainSeatService.selectByTrainCode(train.getCode());
        if(CollUtil.isEmpty(trainSeatList)) {
            LOG.info("火车座位基础数据为空");
            return;
        }

        // 3.根据日期和车次查询每日高铁经停站数据
        List<DailyTrainStation> dailyTrainStationList = dailyTrainStationService.selectByDateAndTrainCode(date, train.getCode());

        // 4.遍历座位数据并插入
        DateTime now = DateTime.now();
        for(TrainSeat trainSeat : trainSeatList) {
            DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(trainSeat, DailyTrainSeat.class);
            dailyTrainSeat.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainSeat.setDate(date);
            // 使用01表示座位是否被购买，其sell长度是经停站size-1
            dailyTrainSeat.setSell(StrUtil.fillBefore("", '0', dailyTrainStationList.size() - 1));
            dailyTrainSeat.setCreateTime(now);
            dailyTrainSeat.setUpdateTime(now);
            dailyTrainSeatMapper.insert(dailyTrainSeat);
        }

        LOG.info("生成日期【{}】车次【{}】的座位信息结束", DateUtil.formatDate(date), train.getCode());
    }

    /**
     * 根据日期和车次，统计每日高铁座位数
     * @param date
     * @param trainCode
     * @return
     */
    @Override
    public int countSeat(Date date, String trainCode) {
        return countSeat(date, trainCode, null);
    }

    /**
     * 根据日期、车次和座位类型，统计每日高铁座位数
     * @param date
     * @param trainCode
     * @param seatType
     * @return
     */
    @Override
    public int countSeat(Date date, String trainCode, String seatType) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        DailyTrainSeatExample.Criteria criteria = dailyTrainSeatExample.createCriteria();
        criteria.andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode);
        if(StrUtil.isNotBlank(seatType)) {
            criteria.andSeatTypeEqualTo(seatType);
        }
        long l = dailyTrainSeatMapper.countByExample(dailyTrainSeatExample);
        if(l == 0L) {
            return -1;
        } else {
            return (int)l;
        }
    }

    /**
     * 根据日期、车次、车厢索引，查询对应的车厢数据
     * @param date
     * @param trainCode
     * @param index
     * @return
     */
    @Override
    public List<DailyTrainSeat> selectByCarriage(Date date, String trainCode, Integer index) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andCarriageIndexEqualTo(index);
        return dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);
    }

    /**
     * 判断每日高铁座位是否存在
     * @param dailyTrainSeat
     * @return
     */
    private boolean isExist(DailyTrainSeat dailyTrainSeat) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(dailyTrainSeat.getDate())
                .andTrainCodeEqualTo(dailyTrainSeat.getTrainCode());
        List<DailyTrainSeat> list = dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);
        if(CollUtil.isNotEmpty(list)) return true;
        else return false;
    }
}
